package com.zrrd.gmall.payment.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradePageRefundModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.zrrd.gmall.model.enums.PaymentType;
import com.zrrd.gmall.model.order.OrderInfo;
import com.zrrd.gmall.order.feign.OrderFeignClient;
import com.zrrd.gmall.payment.config.AlipayConfig;
import com.zrrd.gmall.payment.service.AlipayService;
import com.zrrd.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AlipayServiceImpl implements AlipayService {
    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private AlipayClient alipayClient;
    @Override
    public String createAliPay(Long orderId) throws AlipayApiException {
        //基本信息
        OrderInfo orderInfo = orderFeignClient.getOrderInfo(orderId);
        //保存交易记录
        paymentService.savePaymentInfo(orderInfo, PaymentType.ALIPAY.name());
        //生成二维码
        AlipayTradePagePayRequest aliPageRequest = new AlipayTradePagePayRequest();
        //设置同步回调地址
        aliPageRequest.setReturnUrl(AlipayConfig.return_payment_url);
        //异步
        aliPageRequest.setNotifyUrl(AlipayConfig.notify_payment_url);
        //map集合保存参数
        Map<String,Object> map = new HashMap<>();
        map.put("out_trade_no",orderInfo.getOutTradeNo());
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        map.put("total_amount",0.01);
        map.put("subject",orderInfo.getTradeBody());
        //设置参数
        aliPageRequest.setBizContent(JSON.toJSONString(map));

        return alipayClient.pageExecute(aliPageRequest).getBody();
    }
}
